// 商品合约ABI
const goodsABI = [
    {
        "constant": false,
        "inputs": [
            {
                "name": "goodsId",
                "type": "uint64"
            }
        ],
        "name": "removeGoods",
        "outputs": [],
        "payable": false,
        "stateMutability": "nonpayable",
        "type": "function"
    },
    {
        "constant": false,
        "inputs": [
            {
                "name": "goodsId",
                "type": "uint64"
            },
            {
                "name": "name",
                "type": "string"
            },
            {
                "name": "description",
                "type": "string"
            }
        ],
        "name": "updateGoods",
        "outputs": [],
        "payable": false,
        "stateMutability": "nonpayable",
        "type": "function"
    },
    {
        "constant": false,
        "inputs": [
            {
                "name": "name",
                "type": "string"
            },
            {
                "name": "description",
                "type": "string"
            }
        ],
        "name": "addGoods",
        "outputs": [],
        "payable": false,
        "stateMutability": "nonpayable",
        "type": "function"
    },
    {
        "constant": false,
        "inputs": [
            {
                "name": "goodsId",
                "type": "uint64"
            },
            {
                "name": "to",
                "type": "address"
            }
        ],
        "name": "transferGoods",
        "outputs": [],
        "payable": false,
        "stateMutability": "nonpayable",
        "type": "function"
    },
    {
        "constant": true,
        "inputs": [],
        "name": "owner",
        "outputs": [
            {
                "name": "",
                "type": "address"
            }
        ],
        "payable": false,
        "stateMutability": "view",
        "type": "function"
    },
    {
        "constant": true,
        "inputs": [
            {
                "name": "goodsId",
                "type": "uint64"
            }
        ],
        "name": "getGoods",
        "outputs": [
            {
                "name": "",
                "type": "uint64"
            },
            {
                "name": "",
                "type": "string"
            },
            {
                "name": "",
                "type": "string"
            },
            {
                "name": "",
                "type": "address"
            },
            {
                "name": "",
                "type": "address[]"
            },
            {
                "name": "",
                "type": "uint256"
            },
            {
                "name": "",
                "type": "uint256[]"
            }
        ],
        "payable": false,
        "stateMutability": "view",
        "type": "function"
    },
    {
        "constant": false,
        "inputs": [],
        "name": "resetGoodsId",
        "outputs": [],
        "payable": false,
        "stateMutability": "nonpayable",
        "type": "function"
    },
    {
        "inputs": [],
        "payable": false,
        "stateMutability": "nonpayable",
        "type": "constructor"
    },
    {
        "anonymous": false,
        "inputs": [
            {
                "indexed": false,
                "name": "goodsId",
                "type": "uint64"
            },
            {
                "indexed": false,
                "name": "name",
                "type": "string"
            },
            {
                "indexed": false,
                "name": "owner",
                "type": "address"
            }
        ],
        "name": "GoodsCreated",
        "type": "event"
    },
    {
        "anonymous": false,
        "inputs": [
            {
                "indexed": false,
                "name": "goodsId",
                "type": "uint64"
            },
            {
                "indexed": false,
                "name": "from",
                "type": "address"
            },
            {
                "indexed": false,
                "name": "to",
                "type": "address"
            }
        ],
        "name": "GoodsTransferred",
        "type": "event"
    },
    {
        "anonymous": false,
        "inputs": [
            {
                "indexed": false,
                "name": "goodsId",
                "type": "uint64"
            },
            {
                "indexed": false,
                "name": "name",
                "type": "string"
            },
            {
                "indexed": false,
                "name": "description",
                "type": "string"
            }
        ],
        "name": "GoodsUpdated",
        "type": "event"
    },
    {
        "anonymous": false,
        "inputs": [
            {
                "indexed": false,
                "name": "oldId",
                "type": "uint64"
            },
            {
                "indexed": false,
                "name": "newId",
                "type": "uint64"
            }
        ],
        "name": "GoodsIdReset",
        "type": "event"
    }
];

// 商品合约地址（来自 application.properties 中的配置）
const goodsContractAddress = '0x009bdc6b183667344c5aefab63276c8c7d254157';

// Web3 初始化（使用 FISCO BCOS 的 HTTP 提供者）
let web3;
let goodsContract;
let account;

// 账户映射表
const accountsMap = {
    "0xea4ee062ca6fc4301b62271438f700099148cf50": "Zion",
    "0x3296130386cb5dd29529abcd950d5d8be19a37f7": "hardenJames",
    "0xd6690e17b2478ffb7537a5f19791ecd8a03adb69": "kwahi",
    "0x6a36fae9e871b9a40ecd626f0f283d4c485c624e": "Murray",
    "0x79f8353bae625f087e8696565cf64d5789653d93": "cjmccollum"
};

// 获取当前选择的账户地址
function getCurrentAccount() {
    return document.getElementById('accountSelect').value;
}

// 获取当前账户名称
function getCurrentAccountName() {
    const address = getCurrentAccount();
    return accountsMap[address] || "未知账户";
}

// 更新账户显示信息
function updateAccountDisplay() {
    const address = getCurrentAccount();
    const name = getCurrentAccountName();
    
    document.getElementById('accountName').textContent = name;
    document.getElementById('accountAddress').textContent = address;
}

// 初始化 Web3
async function initWeb3() {
    try {
        // 使用后台API为中转，避免跨域问题
        const response = await fetch('/api/web3/account');
        const data = await response.json();
        
        if (data.success) {
            account = data.account;
            
            // 使用服务器作为代理与FISCO BCOS通信
            web3 = new Web3(new Web3.providers.HttpProvider('/api/web3/jsonrpc'));
            
            // 初始化合约
            goodsContract = new web3.eth.Contract(goodsABI, goodsContractAddress);
            
            console.log("Web3初始化成功，默认账户:", account);
            return true;
        } else {
            showError("初始化Web3失败: " + data.message);
            return false;
        }
    } catch (error) {
        showError("初始化Web3失败: " + error.message);
        return false;
    }
}

// 显示错误信息
function showError(message, elementId = null) {
    console.error(message);
    if (elementId) {
        document.getElementById(elementId).innerHTML = `<div class="alert alert-danger"><i class="bi bi-exclamation-triangle"></i> ${message}</div>`;
    }
}

// 添加商品
async function addGoods() {
    const name = document.getElementById('addName').value.trim();
    const description = document.getElementById('addDescription').value.trim();
    const resultElement = document.getElementById('addResult');
    
    if (!name) {
        showError("请输入商品名称", 'addResult');
        return;
    }
    
    try {
        resultElement.innerHTML = "<div class='alert alert-info'><i class='bi bi-hourglass-split'></i> 处理中，请稍候...</div>";
        
        const response = await fetch('/api/goods/add', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                name: name,
                description: description,
                account: getCurrentAccount()
            })
        });
        
        const data = await response.json();
        
        if (data.success) {
            resultElement.innerHTML = `
                <div class="alert alert-success">
                    <div class="d-flex align-items-center mb-2">
                        <i class="bi bi-check-circle-fill fs-4 me-2"></i>
                        <h5 class="mb-0">添加成功!</h5>
                    </div>
                    <div class="card mt-2 mb-2">
                        <div class="card-body p-3">
                            <div class="row mb-2">
                                <div class="col-md-4 fw-bold"><i class="bi bi-hash"></i> 交易哈希:</div>
                                <div class="col-md-8 text-break"><code>${data.txHash}</code></div>
                            </div>
                            <div class="row mb-2">
                                <div class="col-md-4 fw-bold"><i class="bi bi-box-seam"></i> 商品ID:</div>
                                <div class="col-md-8"><span class="badge bg-success">${data.goodsId}</span></div>
                            </div>
                            <div class="row">
                                <div class="col-md-4 fw-bold"><i class="bi bi-person"></i> 账户:</div>
                                <div class="col-md-8">
                                    <span class="badge bg-primary">${getCurrentAccountName()}</span>
                                    <span class="text-muted">(${getCurrentAccount().substring(0, 10)}...)</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            // 清空输入框
            document.getElementById('addName').value = '';
            document.getElementById('addDescription').value = '';
            
            // 添加商品后自动刷新列表
            setTimeout(() => {
                getGoodsList();
            }, 1000);
        } else {
            showError("添加商品失败: " + data.message, 'addResult');
        }
    } catch (error) {
        showError("添加商品时发生错误: " + error.message, 'addResult');
    }
}

// 查询商品
async function queryGoods() {
    const goodsId = document.getElementById('queryId').value.trim();
    const resultElement = document.getElementById('queryResult');
    
    if (!goodsId) {
        showError("请输入商品ID", 'queryResult');
        return;
    }
    
    try {
        resultElement.innerHTML = "<div class='alert alert-info'><i class='bi bi-hourglass-split'></i> 查询中，请稍候...</div>";
        
        const response = await fetch(`/api/goods/get?goodsId=${goodsId}&account=${getCurrentAccount()}`);
        const data = await response.json();
        
        // 添加调试信息，在控制台打印接收到的数据
        console.log("从后端接收的商品数据:", data);
        if (data.goods) {
            console.log("商品详细信息:", data.goods);
            console.log("历史所有者数组:", data.goods.historyOwners);
            console.log("历史所有者类型:", data.goods.historyOwners ? typeof data.goods.historyOwners : "未定义");
            console.log("历史所有者数量:", data.goods.historyOwners ? data.goods.historyOwners.length : 0);
            console.log("时间戳数组:", data.goods.ownershipTimestamps);
            console.log("时间戳类型:", data.goods.ownershipTimestamps ? typeof data.goods.ownershipTimestamps : "未定义");
            console.log("时间戳数量:", data.goods.ownershipTimestamps ? data.goods.ownershipTimestamps.length : 0);
        }
        
        if (data.success) {
            const goods = data.goods;
            const ownerName = accountsMap[goods.owner] || "未知账户";
            
            // 正确处理创建时间
            let createTimeStr = "未知时间";
            if (goods.createTime) {
                // 检查时间戳长度来确定是秒还是毫秒
                let timestamp = goods.createTime;
                // 如果时间戳长度小于13，说明是秒级时间戳，需要转换为毫秒
                if (timestamp.toString().length < 13) {
                    timestamp = timestamp * 1000;
                }
                
                try {
                    const createDate = new Date(timestamp);
                    // 检查日期是否有效
                    if (!isNaN(createDate.getTime())) {
                        createTimeStr = createDate.toLocaleString('zh-CN', {
                            year: 'numeric',
                            month: '2-digit',
                            day: '2-digit',
                            hour: '2-digit',
                            minute: '2-digit',
                            second: '2-digit',
                            hour12: false
                        });
                    }
                } catch (e) {
                    console.error("时间戳转换错误:", e);
                    createTimeStr = "时间格式错误: " + goods.createTime;
                }
            }
            
            // 确保historyOwners存在且是数组
            if (!goods.historyOwners || !Array.isArray(goods.historyOwners)) {
                goods.historyOwners = [];
                console.warn("historyOwners不存在或不是数组，已初始化为空数组");
            }
            
            // 确保ownershipTimestamps存在且是数组
            if (!goods.ownershipTimestamps || !Array.isArray(goods.ownershipTimestamps)) {
                goods.ownershipTimestamps = [];
                console.warn("ownershipTimestamps不存在或不是数组，已初始化为空数组");
            }
            
            // 处理历史所有者列表
            let historyOwnersHtml = '';
            if (goods.historyOwners && goods.historyOwners.length > 0) {
                historyOwnersHtml += '<div class="mt-4">';
                historyOwnersHtml += '<h5><i class="bi bi-clock-history"></i> 历史所有者变更记录</h5>';
                historyOwnersHtml += '<div class="history-list">';
                historyOwnersHtml += '<ul class="list-group">';
                
                // 反向显示历史，最新的在最前面
                const reversedHistory = [...goods.historyOwners].reverse();
                
                // 同样反转时间戳数组，保持与所有者记录同步
                // 修改判断条件，确保时间戳数组存在
                let reversedTimestamps = [];
                if (Array.isArray(goods.ownershipTimestamps) && goods.ownershipTimestamps.length > 0) {
                    reversedTimestamps = [...goods.ownershipTimestamps].reverse();
                }
                
                console.log("反转后的历史所有者:", reversedHistory);
                console.log("反转后的时间戳:", reversedTimestamps);
                
                reversedHistory.forEach((ownerAddress, index) => {
                    const historyOwnerName = accountsMap[ownerAddress] || "未知账户";
                    const actualIndex = goods.historyOwners.length - index;
                    
                    // 处理转移时间戳
                    let transferTimeStr = '<span class="text-muted"><i class="bi bi-question-circle"></i> 时间信息不可用</span>';
                    // 检查时间戳是否存在
                    if (reversedTimestamps && index < reversedTimestamps.length) {
                        let timestamp = reversedTimestamps[index];
                        if (timestamp) {
                            // 如果时间戳长度小于13，说明是秒级时间戳，需要转换为毫秒
                            if (timestamp.toString().length < 13) {
                                timestamp = timestamp * 1000;
                            }
                            
                            try {
                                const transferDate = new Date(timestamp);
                                // 检查日期是否有效
                                if (!isNaN(transferDate.getTime())) {
                                    transferTimeStr = `<span class="text-success">
                                        <i class="bi bi-clock"></i> ${transferDate.toLocaleString('zh-CN', {
                                            year: 'numeric',
                                            month: '2-digit',
                                            day: '2-digit',
                                            hour: '2-digit',
                                            minute: '2-digit',
                                            second: '2-digit',
                                            hour12: false
                                        })}
                                    </span>`;
                                }
                            } catch (e) {
                                console.error("转移时间戳转换错误:", e);
                                transferTimeStr = `<span class="text-danger">
                                    <i class="bi bi-exclamation-triangle"></i> 时间格式错误: ${timestamp}
                                </span>`;
                            }
                        }
                    }
                    
                    historyOwnersHtml += `
                        <li class="list-group-item">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <span class="badge bg-secondary me-2">${actualIndex}</span>
                                    <i class="bi bi-person-fill me-1"></i> 
                                    <strong>${historyOwnerName}</strong>
                                </div>
                                <span class="badge bg-info text-white">所有者</span>
                            </div>
                            <div class="text-muted mt-1">
                                <i class="bi bi-key-fill me-1"></i> ${ownerAddress}
                            </div>
                            <div class="mt-1 d-flex justify-content-between">
                                <div>${transferTimeStr}</div>
                                <div>
                                    <span class="badge bg-info text-white">
                                        <i class="bi bi-arrow-right-circle"></i> 所有权转移
                                    </span>
                                </div>
                            </div>
                        </li>
                    `;
                });
                
                historyOwnersHtml += '</ul>';
                historyOwnersHtml += '</div>';
                
                historyOwnersHtml += '</div>';
            } else {
                historyOwnersHtml = `
                    <div class="mt-4">
                        <h5><i class="bi bi-clock-history"></i> 历史所有者记录</h5>
                        <div class="alert alert-light">
                            <i class="bi bi-info-circle me-2"></i> 该商品无转移记录
                        </div>
                    </div>
                `;
            }
            
            resultElement.innerHTML = `
                <div class="alert alert-success">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h5 class="mb-0"><i class="bi bi-box-seam"></i> 商品基本信息</h5>
                        <span class="badge bg-success">ID: ${goods.id}</span>
                    </div>
                    
                    <div class="card mb-3">
                        <div class="card-body p-3">
                            <div class="row mb-2">
                                <div class="col-md-3 fw-bold"><i class="bi bi-tag"></i> 名称:</div>
                                <div class="col-md-9">${goods.name}</div>
                            </div>
                            <div class="row mb-2">
                                <div class="col-md-3 fw-bold"><i class="bi bi-card-text"></i> 描述:</div>
                                <div class="col-md-9">${goods.description || '<span class="text-muted">无描述</span>'}</div>
                            </div>
                            <div class="row mb-2">
                                <div class="col-md-3 fw-bold"><i class="bi bi-person"></i> 当前所有者:</div>
                                <div class="col-md-9">
                                    <span class="badge bg-primary me-2">${ownerName}</span>
                                    <span class="text-muted">${goods.owner}</span>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-3 fw-bold"><i class="bi bi-calendar"></i> 创建时间:</div>
                                <div class="col-md-9">${createTimeStr}</div>
                            </div>
                        </div>
                    </div>
                    
                    ${historyOwnersHtml}
                </div>
            `;
        } else {
            showError(`<i class="bi bi-exclamation-triangle"></i> 查询商品失败: ${data.message}`, 'queryResult');
        }
    } catch (error) {
        showError(`<i class="bi bi-exclamation-triangle"></i> 查询商品时发生错误: ${error.message}`, 'queryResult');
    }
}

// 更新商品
async function updateGoods() {
    const goodsId = document.getElementById('updateId').value.trim();
    const name = document.getElementById('updateName').value.trim();
    const description = document.getElementById('updateDescription').value.trim();
    const resultElement = document.getElementById('updateResult');
    
    if (!goodsId) {
        showError("请输入商品ID", 'updateResult');
        return;
    }
    
    if (!name) {
        showError("请输入商品名称", 'updateResult');
        return;
    }
    
    try {
        // 先检查当前用户是否是商品的所有者
        resultElement.innerHTML = "<div class='alert alert-info'><i class='bi bi-hourglass-split'></i> 检查权限中...</div>";
        
        const checkResponse = await fetch(`/api/goods/get?goodsId=${goodsId}&account=${getCurrentAccount()}`);
        const checkData = await checkResponse.json();
        
        if (!checkData.success) {
            showError(`查询商品失败: ${checkData.message}`, 'updateResult');
            return;
        }
        
        // 验证商品所有权
        if (checkData.goods && checkData.goods.owner !== getCurrentAccount()) {
            showError(`<i class="bi bi-shield-exclamation"></i> 权限错误: 您不是此商品的所有者，无法更新`, 'updateResult');
            return;
        }
        
        // 权限验证通过，执行更新操作
        resultElement.innerHTML = "<div class='alert alert-info'><i class='bi bi-hourglass-split'></i> 权限验证通过，处理中...</div>";
        
        const response = await fetch('/api/goods/update', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                goodsId: goodsId,
                name: name,
                description: description,
                account: getCurrentAccount()
            })
        });
        
        const data = await response.json();
        
        if (data.success) {
            resultElement.innerHTML = `
                <div class="alert alert-success">
                    <div class="d-flex align-items-center mb-2">
                        <i class="bi bi-check-circle-fill fs-4 me-2"></i>
                        <h5 class="mb-0">更新成功!</h5>
                    </div>
                    <div class="card mt-2 mb-2">
                        <div class="card-body p-3">
                            <div class="row mb-2">
                                <div class="col-md-4 fw-bold"><i class="bi bi-hash"></i> 交易哈希:</div>
                                <div class="col-md-8 text-break"><code>${data.txHash}</code></div>
                            </div>
                            <div class="row mb-2">
                                <div class="col-md-4 fw-bold"><i class="bi bi-box-seam"></i> 商品ID:</div>
                                <div class="col-md-8"><span class="badge bg-success">${goodsId}</span></div>
                            </div>
                            <div class="row">
                                <div class="col-md-4 fw-bold"><i class="bi bi-person"></i> 账户:</div>
                                <div class="col-md-8">
                                    <span class="badge bg-primary">${getCurrentAccountName()}</span>
                                    <span class="text-muted">(${getCurrentAccount().substring(0, 10)}...)</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            // 清空输入框
            document.getElementById('updateId').value = '';
            document.getElementById('updateName').value = '';
            document.getElementById('updateDescription').value = '';
            
            // 更新商品后自动刷新列表
            setTimeout(() => {
                getGoodsList();
            }, 1000);
        } else {
            showError(`<i class="bi bi-exclamation-triangle"></i> 更新商品失败: ${data.message}`, 'updateResult');
        }
    } catch (error) {
        showError(`<i class="bi bi-exclamation-triangle"></i> 更新商品时发生错误: ${error.message}`, 'updateResult');
    }
}

// 转移商品
async function transferGoods() {
    const goodsId = document.getElementById('transferId').value.trim();
    const toAddress = document.getElementById('transferTo').value.trim();
    const resultElement = document.getElementById('transferResult');
    
    if (!goodsId) {
        showError("请输入商品ID", 'transferResult');
        return;
    }
    
    if (!toAddress) {
        showError("请选择接收者地址", 'transferResult');
        return;
    }
    
    // 检查是否向自己转移
    if (toAddress === getCurrentAccount()) {
        showError("不能向自己转移商品", 'transferResult');
        return;
    }
    
    try {
        // 先检查当前用户是否是商品的所有者
        resultElement.innerHTML = "<div class='alert alert-info'><i class='bi bi-hourglass-split'></i> 检查权限中...</div>";
        
        const checkResponse = await fetch(`/api/goods/get?goodsId=${goodsId}&account=${getCurrentAccount()}`);
        const checkData = await checkResponse.json();
        
        if (!checkData.success) {
            showError(`查询商品失败: ${checkData.message}`, 'transferResult');
            return;
        }
        
        // 验证商品所有权
        if (checkData.goods && checkData.goods.owner !== getCurrentAccount()) {
            showError(`<i class="bi bi-shield-exclamation"></i> 权限错误: 您不是此商品的所有者，无法转移`, 'transferResult');
            return;
        }
        
        // 权限验证通过，执行转移操作
        resultElement.innerHTML = "<div class='alert alert-info'><i class='bi bi-hourglass-split'></i> 权限验证通过，处理中...</div>";
        
        const response = await fetch('/api/goods/transfer', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                goodsId: goodsId,
                to: toAddress,
                account: getCurrentAccount()
            })
        });
        
        const data = await response.json();
        
        if (data.success) {
            const toAccountName = accountsMap[toAddress] || "未知账户";
            
            resultElement.innerHTML = `
                <div class="alert alert-success">
                    <div class="d-flex align-items-center mb-2">
                        <i class="bi bi-check-circle-fill fs-4 me-2"></i>
                        <h5 class="mb-0">转移成功!</h5>
                    </div>
                    <div class="card mt-2 mb-2">
                        <div class="card-body p-3">
                            <div class="row mb-2">
                                <div class="col-md-4 fw-bold"><i class="bi bi-hash"></i> 交易哈希:</div>
                                <div class="col-md-8 text-break"><code>${data.txHash}</code></div>
                            </div>
                            <div class="row mb-2">
                                <div class="col-md-4 fw-bold"><i class="bi bi-box-seam"></i> 商品ID:</div>
                                <div class="col-md-8"><span class="badge bg-success">${goodsId}</span></div>
                            </div>
                            <div class="row mb-2">
                                <div class="col-md-4 fw-bold"><i class="bi bi-arrow-up-right"></i> 发送方:</div>
                                <div class="col-md-8">
                                    <span class="badge bg-secondary">${getCurrentAccountName()}</span>
                                    <span class="text-muted">(${getCurrentAccount().substring(0, 10)}...)</span>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-4 fw-bold"><i class="bi bi-arrow-down-right"></i> 接收方:</div>
                                <div class="col-md-8">
                                    <span class="badge bg-primary">${toAccountName}</span>
                                    <span class="text-muted">(${toAddress.substring(0, 10)}...)</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            // 清空输入框
            document.getElementById('transferId').value = '';
            
            // 转移商品后自动刷新列表
            setTimeout(() => {
                getGoodsList();
            }, 1000);
        } else {
            showError(`<i class="bi bi-exclamation-triangle"></i> 转移商品失败: ${data.message}`, 'transferResult');
        }
    } catch (error) {
        showError(`<i class="bi bi-exclamation-triangle"></i> 转移商品时发生错误: ${error.message}`, 'transferResult');
    }
}

// 移除商品
async function removeGoods() {
    const goodsId = document.getElementById('removeId').value.trim();
    const resultElement = document.getElementById('removeResult');
    
    if (!goodsId) {
        showError("请输入商品ID", 'removeResult');
        return;
    }
    
    if (!confirm("确定要移除ID为 " + goodsId + " 的商品吗？此操作不可恢复！")) {
        return;
    }
    
    try {
        // 先检查当前用户是否是商品的所有者
        resultElement.innerHTML = "<div class='alert alert-info'><i class='bi bi-hourglass-split'></i> 检查权限中...</div>";
        
        const checkResponse = await fetch(`/api/goods/get?goodsId=${goodsId}&account=${getCurrentAccount()}`);
        const checkData = await checkResponse.json();
        
        if (!checkData.success) {
            showError(`查询商品失败: ${checkData.message}`, 'removeResult');
            return;
        }
        
        // 验证商品所有权
        if (checkData.goods && checkData.goods.owner !== getCurrentAccount()) {
            showError(`<i class="bi bi-shield-exclamation"></i> 权限错误: 您不是此商品的所有者，无法删除`, 'removeResult');
            return;
        }
        
        // 权限验证通过，执行删除操作
        resultElement.innerHTML = "<div class='alert alert-info'><i class='bi bi-hourglass-split'></i> 权限验证通过，处理中...</div>";
        
        const response = await fetch('/api/goods/remove', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                goodsId: goodsId,
                account: getCurrentAccount()
            })
        });
        
        const data = await response.json();
        
        if (data.success) {
            resultElement.innerHTML = `
                <div class="alert alert-success">
                    <div class="d-flex align-items-center mb-2">
                        <i class="bi bi-check-circle-fill fs-4 me-2"></i>
                        <h5 class="mb-0">删除成功!</h5>
                    </div>
                    <div class="card mt-2 mb-2">
                        <div class="card-body p-3">
                            <div class="row mb-2">
                                <div class="col-md-4 fw-bold"><i class="bi bi-hash"></i> 交易哈希:</div>
                                <div class="col-md-8 text-break"><code>${data.txHash}</code></div>
                            </div>
                            <div class="row mb-2">
                                <div class="col-md-4 fw-bold"><i class="bi bi-box-seam"></i> 商品ID:</div>
                                <div class="col-md-8"><span class="badge bg-danger">${goodsId}</span></div>
                            </div>
                            <div class="row">
                                <div class="col-md-4 fw-bold"><i class="bi bi-person"></i> 账户:</div>
                                <div class="col-md-8">
                                    <span class="badge bg-primary">${getCurrentAccountName()}</span>
                                    <span class="text-muted">(${getCurrentAccount().substring(0, 10)}...)</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            // 清空输入框
            document.getElementById('removeId').value = '';
            
            // 删除商品后自动刷新列表
            setTimeout(() => {
                getGoodsList();
            }, 1000);
        } else {
            showError(`<i class="bi bi-exclamation-triangle"></i> 删除商品失败: ${data.message}`, 'removeResult');
        }
    } catch (error) {
        showError(`<i class="bi bi-exclamation-triangle"></i> 删除商品时发生错误: ${error.message}`, 'removeResult');
    }
}

// 重置商品ID
async function resetGoodsId() {
    const resultElement = document.getElementById('resetResult');
    
    if (!confirm("确定要重置商品ID吗？此操作会影响系统中所有新增商品的ID！")) {
        return;
    }
    
    try {
        // 假设只有特定账户可以重置商品ID
        const adminAccounts = ["0xea4ee062ca6fc4301b62271438f700099148cf50"]; // 假设Zion是管理员
        if (!adminAccounts.includes(getCurrentAccount())) {
            showError(`<i class="bi bi-shield-exclamation"></i> 权限错误: 您没有管理员权限，无法重置商品ID`, 'resetResult');
            return;
        }
        
        resultElement.innerHTML = "<div class='alert alert-info'><i class='bi bi-hourglass-split'></i> 处理中，请稍候...</div>";
        
        const response = await fetch('/api/goods/reset', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                account: getCurrentAccount()
            })
        });
        
        const data = await response.json();
        
        if (data.success) {
            resultElement.innerHTML = `
                <div class="alert alert-success">
                    <div class="d-flex align-items-center mb-2">
                        <i class="bi bi-check-circle-fill fs-4 me-2"></i>
                        <h5 class="mb-0">重置成功!</h5>
                    </div>
                    <div class="card mt-2 mb-2">
                        <div class="card-body p-3">
                            <div class="row mb-2">
                                <div class="col-md-4 fw-bold"><i class="bi bi-hash"></i> 交易哈希:</div>
                                <div class="col-md-8 text-break"><code>${data.txHash}</code></div>
                            </div>
                            <div class="row mb-2">
                                <div class="col-md-4 fw-bold"><i class="bi bi-arrow-left"></i> 旧ID值:</div>
                                <div class="col-md-8"><span class="badge bg-secondary">${data.oldId}</span></div>
                            </div>
                            <div class="row mb-2">
                                <div class="col-md-4 fw-bold"><i class="bi bi-arrow-right"></i> 新ID值:</div>
                                <div class="col-md-8"><span class="badge bg-success">${data.newId}</span></div>
                            </div>
                            <div class="row">
                                <div class="col-md-4 fw-bold"><i class="bi bi-person"></i> 操作账户:</div>
                                <div class="col-md-8">
                                    <span class="badge bg-primary">${getCurrentAccountName()}</span>
                                    <span class="text-muted">(${getCurrentAccount().substring(0, 10)}...)</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
        } else {
            showError(`<i class="bi bi-exclamation-triangle"></i> 重置商品ID失败: ${data.message}`, 'resetResult');
        }
    } catch (error) {
        showError(`<i class="bi bi-exclamation-triangle"></i> 重置商品ID时发生错误: ${error.message}`, 'resetResult');
    }
}

// 处理账户选择变更
function handleAccountChange() {
    updateAccountDisplay();
    console.log(`切换到账户: ${getCurrentAccountName()} (${getCurrentAccount()})`);
    
    // 切换账户后自动刷新商品列表
    getGoodsList();
}

// 获取所有商品列表
async function getGoodsList() {
    const listElement = document.getElementById('goodsList');
    const infoElement = document.getElementById('goodsListInfo');
    
    try {
        // 初始化加载动画
        listElement.innerHTML = `
            <tr>
                <td colspan="5" class="text-center py-4">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                    <p class="mt-2 text-muted">正在加载商品列表...</p>
                </td>
            </tr>
        `;
        
        infoElement.textContent = `加载商品数据中...`;
        
        // 严格递增查询商品，确保每个ID只查询一次
        const goodsList = [];
        const maxIdToTry = 30; // 最大尝试ID
        
        // 已查询过的ID集合
        const queriedIds = new Set();
        
        // 逐个ID查询
        for (let id = 0; id < maxIdToTry; id++) {
            // 确保每个ID只查询一次
            if (queriedIds.has(id)) {
                console.log(`ID为${id}的商品已查询过，跳过`);
                continue;
            }
            
            queriedIds.add(id); // 标记为已查询
            
            try {
                const response = await fetch(`/api/goods/get?goodsId=${id}&account=${getCurrentAccount()}`);
                const data = await response.json();
                
                if (data.success && data.goods) {
                    // 确保ID是数字类型
                    const goods = data.goods;
                    goods.id = Number(id); // 强制使用循环中的id，避免类型不一致
                    
                    // 确保historyOwners和ownershipTimestamps存在且是数组
                    if (!goods.historyOwners || !Array.isArray(goods.historyOwners)) {
                        goods.historyOwners = [];
                    }
                    
                    if (!goods.ownershipTimestamps || !Array.isArray(goods.ownershipTimestamps)) {
                        goods.ownershipTimestamps = [];
                    }
                    
                    // 添加调试信息
                    console.log(`ID=${id} 的商品历史所有者数量:`, goods.historyOwners.length);
                    console.log(`ID=${id} 的商品时间戳数量:`, goods.ownershipTimestamps.length);
                    
                    goodsList.push(goods);
                    
                    // 更新加载状态
                    infoElement.textContent = `已找到 ${goodsList.length} 个商品...`;
                }
            } catch (e) {
                console.log(`ID为${id}的商品查询失败:`, e.message);
                // 查询失败，继续下一个ID
            }
        }
        
        // 按ID排序，确保即使后端返回数据乱序也能正确排列
        goodsList.sort((a, b) => {
            // 将ID转换为数字进行比较
            let idA = parseInt(a.id, 10);
            let idB = parseInt(b.id, 10);
            // 增加调试信息
            console.log(`排序比较: ID ${idA} vs ID ${idB}, 结果: ${idA - idB}`);
            return idA - idB;
        });
        
        // 处理排序后的结果
        processGoodsList(goodsList, listElement, infoElement);
    } catch (error) {
        listElement.innerHTML = `
            <tr>
                <td colspan="5" class="text-center py-4">
                    <div class="alert alert-danger mb-0">
                        <i class="bi bi-exclamation-triangle-fill me-2"></i>
                        加载商品列表失败: ${error.message}
                    </div>
                </td>
            </tr>
        `;
        infoElement.textContent = `加载失败`;
        console.error("加载商品列表时发生错误:", error);
    }
}

// 处理和显示商品列表
function processGoodsList(goodsList, listElement, infoElement) {
    // 根据结果更新表格
    if (!goodsList || goodsList.length === 0) {
        listElement.innerHTML = `
            <tr>
                <td colspan="5" class="text-center py-4">
                    <i class="bi bi-inbox fs-3 text-muted"></i>
                    <p class="mt-2 text-muted">暂无商品数据</p>
                </td>
            </tr>
        `;
        infoElement.textContent = `未找到有效商品记录`;
        return;
    }
    
    // 记录一下每个ID，确认是否有序
    console.log("商品ID列表:");
    goodsList.forEach(goods => {
        console.log(`ID: ${goods.id}, 名称: ${goods.name}`);
    });
    
    // 生成表格HTML
    let tableHtml = '';
    goodsList.forEach(goods => {
        const ownerName = accountsMap[goods.owner] || "未知账户";
        const description = goods.description ? 
            (goods.description.length > 50 ? goods.description.substring(0, 50) + '...' : goods.description) : 
            '<span class="text-muted">无描述</span>';
        
        // 判断当前用户是否是商品所有者
        const isOwner = goods.owner === getCurrentAccount();
        
        tableHtml += `
            <tr>
                <td>
                    <a href="#" class="view-goods-link" data-goods-id="${goods.id}">
                        ${goods.id}
                    </a>
                </td>
                <td>${goods.name}</td>
                <td>${description}</td>
                <td>
                    <span class="badge bg-primary">${ownerName}</span>
                </td>
                <td>
                    <div class="btn-group btn-group-sm" role="group">
                        <button type="button" class="btn btn-outline-primary view-btn" data-goods-id="${goods.id}" 
                            data-bs-toggle="tooltip" title="查看商品详情">
                            <i class="bi bi-eye"></i>
                        </button>
                        <button type="button" class="btn btn-outline-success transfer-btn" data-goods-id="${goods.id}" 
                            data-bs-toggle="tooltip" title="${isOwner ? '转移所有权' : '您不是商品所有者'}"
                            ${isOwner ? '' : 'disabled'}>
                            <i class="bi bi-arrow-left-right"></i>
                        </button>
                        <button type="button" class="btn btn-outline-danger remove-btn" data-goods-id="${goods.id}"
                            data-bs-toggle="tooltip" title="${isOwner ? '删除商品' : '您不是商品所有者'}"
                            ${isOwner ? '' : 'disabled'}>
                            <i class="bi bi-trash"></i>
                        </button>
                    </div>
                </td>
            </tr>
        `;
    });
    
    listElement.innerHTML = tableHtml;
    
    // 更新动态统计信息
    const totalGoods = goodsList.length;
    const currentUserGoods = goodsList.filter(goods => goods.owner === getCurrentAccount()).length;
    
    infoElement.innerHTML = `
        <div class="d-flex align-items-center">
            <span class="me-3"><i class="bi bi-box-seam me-1"></i> 共找到 <strong>${totalGoods}</strong> 个商品</span>
            <span class="me-3"><i class="bi bi-person-badge me-1"></i> 您拥有 <strong>${currentUserGoods}</strong> 个商品</span>
            <span class="me-3 text-muted small">ID范围: ${goodsList.length > 0 ? `${goodsList[0].id} ~ ${goodsList[goodsList.length-1].id}` : '无'}</span>
        </div>
    `;
    
    // 初始化工具提示
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
    
    // 添加查看商品事件处理
    document.querySelectorAll('.view-goods-link, .view-btn').forEach(element => {
        element.addEventListener('click', function(e) {
            e.preventDefault();
            const goodsId = this.getAttribute('data-goods-id');
            
            // 获取商品信息
            const goods = goodsList.find(g => g.id.toString() === goodsId.toString());
            if (!goods) return;
            
            // 创建详情弹窗
            const modal = createGoodsModal(goods, '查看商品详情');
            document.body.appendChild(modal);
            
            // 显示模态框
            const bsModal = new bootstrap.Modal(modal);
            bsModal.show();
            
            // 模态框关闭后删除DOM元素
            modal.addEventListener('hidden.bs.modal', function() {
                modal.remove();
            });
        });
    });
    
    // 添加转移商品事件处理
    document.querySelectorAll('.transfer-btn').forEach(element => {
        element.addEventListener('click', function() {
            const goodsId = this.getAttribute('data-goods-id');
            
            // 确认是否转移
            alert(`您将要转移ID为 ${goodsId} 的商品。请到转移商品面板完成操作。`);
            
            // 填充ID并滚动到转移面板
            document.getElementById('transferId').value = goodsId;
            document.querySelectorAll('.section-card')[3].scrollIntoView({ behavior: 'smooth' });
        });
    });
    
    // 添加删除商品事件处理
    document.querySelectorAll('.remove-btn').forEach(element => {
        element.addEventListener('click', function() {
            const goodsId = this.getAttribute('data-goods-id');
            
            // 确认是否删除
            if (confirm(`确定要删除ID为 ${goodsId} 的商品吗？此操作不可恢复！`)) {
                // 填充ID并滚动到删除面板
                document.getElementById('removeId').value = goodsId;
                document.getElementById('removeGoodsBtn').click();
            }
        });
    });
}

// 创建商品详情模态框
function createGoodsModal(goods, title) {
    // 获取商品所有者名称
    const ownerName = accountsMap[goods.owner] || "未知账户";
    
    // 格式化创建时间
    let createTimeStr = "未知时间";
    if (goods.createTime) {
        let timestamp = goods.createTime;
        if (timestamp.toString().length < 13) {
            timestamp = timestamp * 1000;
        }
        
        try {
            const createDate = new Date(timestamp);
            if (!isNaN(createDate.getTime())) {
                createTimeStr = createDate.toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit',
                    hour12: false
                });
            }
        } catch (e) {
            createTimeStr = "时间格式错误";
        }
    }
    
    // 创建模态框DOM
    const modalDiv = document.createElement('div');
    modalDiv.className = 'modal fade';
    modalDiv.id = `goodsModal-${goods.id}`;
    modalDiv.tabIndex = -1;
    modalDiv.setAttribute('aria-labelledby', `goodsModalLabel-${goods.id}`);
    modalDiv.setAttribute('aria-hidden', 'true');
    
    // 确保historyOwners和ownershipTimestamps存在且是数组
    if (!goods.historyOwners || !Array.isArray(goods.historyOwners)) {
        goods.historyOwners = [];
        console.warn("模态框中historyOwners不存在或不是数组，已初始化为空数组");
    }
    
    if (!goods.ownershipTimestamps || !Array.isArray(goods.ownershipTimestamps)) {
        goods.ownershipTimestamps = [];
        console.warn("模态框中ownershipTimestamps不存在或不是数组，已初始化为空数组");
    }
    
    // 历史所有者信息
    let historyOwnersHtml = '';
    if (goods.historyOwners && goods.historyOwners.length > 0) {
        console.log("在模态框中显示历史所有者数据:", goods.historyOwners);
        console.log("在模态框中显示时间戳数据:", goods.ownershipTimestamps);
        
        historyOwnersHtml += '<div class="mt-3">';
        historyOwnersHtml += '<h6 class="border-bottom pb-2 mb-2">历史所有者</h6>';
        historyOwnersHtml += '<div class="table-responsive">';
        historyOwnersHtml += '<table class="table table-sm table-bordered table-hover">';
        historyOwnersHtml += `
            <thead class="table-light">
                <tr>
                    <th class="text-center" style="width: 60px;">#</th>
                    <th>所有者</th>
                    <th>地址</th>
                    <th>时间</th>
                </tr>
            </thead>
            <tbody>
        `;
        
        // 历史所有者按顺序显示（从最早到最近）
        goods.historyOwners.forEach((owner, index) => {
            const historyOwnerName = accountsMap[owner] || "未知账户";
            const orderNumber = index + 1; // 顺序编号从1开始
            
            // 时间戳
            let timeInfo = '<span class="text-muted">无时间信息</span>';
            if (goods.ownershipTimestamps && index < goods.ownershipTimestamps.length) {
                let timestamp = goods.ownershipTimestamps[index];
                if (timestamp) {
                    if (timestamp.toString().length < 13) {
                        timestamp = timestamp * 1000;
                    }
                    
                    try {
                        const date = new Date(timestamp);
                        if (!isNaN(date.getTime())) {
                            timeInfo = date.toLocaleString('zh-CN', {
                                year: 'numeric',
                                month: '2-digit',
                                day: '2-digit',
                                hour: '2-digit',
                                minute: '2-digit'
                            });
                        }
                    } catch (e) {
                        timeInfo = '<span class="text-danger">时间格式错误</span>';
                    }
                }
            }
            
            historyOwnersHtml += `
                <tr>
                    <td class="text-center">
                        <span class="badge ${index === 0 ? 'bg-secondary' : 'bg-light text-dark'} rounded-pill">
                            ${orderNumber}
                        </span>
                    </td>
                    <td>
                        <i class="bi bi-person me-1"></i>
                        <span class="badge bg-primary">${historyOwnerName}</span>
                    </td>
                    <td>
                        <span class="small text-muted">${owner}</span>
                    </td>
                    <td>
                        <i class="bi bi-clock me-1"></i>${timeInfo}
                    </td>
                </tr>
            `;
        });
        
        // 添加当前所有者作为最后一条记录（最新）
        const currentOwnerNumber = goods.historyOwners.length + 1;
        historyOwnersHtml += `
            <tr class="table-light">
                <td class="text-center">
                    <span class="badge bg-success rounded-pill">${currentOwnerNumber}</span>
                </td>
                <td>
                    <i class="bi bi-person-check-fill me-1"></i>
                    <span class="badge bg-success">${ownerName} (当前)</span>
                </td>
                <td>
                    <span class="small">${goods.owner}</span>
                </td>
                <td>
                    <i class="bi bi-check-circle me-1"></i>当前所有者
                </td>
            </tr>
        `;
        
        historyOwnersHtml += '</tbody>';
        historyOwnersHtml += '</table>';
        historyOwnersHtml += '</div>';
        historyOwnersHtml += '</div>';
    } else {
        historyOwnersHtml = `
            <div class="mt-3">
                <h6 class="border-bottom pb-2 mb-2">历史所有者</h6>
                <div class="alert alert-light small p-2">
                    <i class="bi bi-info-circle me-2"></i> 该商品无所有权转移记录，当前所有者是第一任所有者
                </div>
                <div class="card bg-light">
                    <div class="card-body py-2">
                        <div class="d-flex align-items-center">
                            <span class="badge bg-success rounded-pill me-2">1</span>
                            <i class="bi bi-person-check-fill me-1"></i>
                            <span class="badge bg-success me-2">${ownerName} (当前/首任)</span>
                            <span class="small text-muted">${goods.owner}</span>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }
    
    // 判断当前用户是否是所有者
    const isOwner = goods.owner === getCurrentAccount();
    
    // 操作按钮（只有拥有者才能看到转移和删除按钮）
    let actionButtonsHtml = `
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
    `;
    
    if (isOwner) {
        actionButtonsHtml += `
            <button type="button" class="btn btn-success transfer-modal-btn" data-goods-id="${goods.id}">
                <i class="bi bi-arrow-left-right me-1"></i> 转移
            </button>
            <button type="button" class="btn btn-danger remove-modal-btn" data-goods-id="${goods.id}">
                <i class="bi bi-trash me-1"></i> 删除
            </button>
        `;
    }
    
    // 模态框内容 - 默认显示详细信息
    modalDiv.innerHTML = `
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="goodsModalLabel-${goods.id}">
                        <i class="bi bi-box-seam me-2"></i>${title}
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
                </div>
                <div class="modal-body">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h6 class="mb-0">${goods.name}</h6>
                        <span class="badge bg-success">ID: ${goods.id}</span>
                    </div>
                    
                    <div class="card mb-3">
                        <div class="card-header bg-light">
                            <i class="bi bi-info-circle me-1"></i> 商品基本信息
                        </div>
                        <div class="card-body">
                            <div class="row mb-2">
                                <div class="col-md-3 fw-bold"><i class="bi bi-card-text me-1"></i> 描述:</div>
                                <div class="col-md-9">${goods.description || '<span class="text-muted">无描述</span>'}</div>
                            </div>
                            
                            <div class="row mb-2">
                                <div class="col-md-3 fw-bold"><i class="bi bi-person me-1"></i> 当前所有者:</div>
                                <div class="col-md-9">
                                    <span class="badge bg-primary me-1">${ownerName}</span>
                                    <span class="text-muted small">${goods.owner}</span>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-3 fw-bold"><i class="bi bi-calendar me-1"></i> 创建时间:</div>
                                <div class="col-md-9">${createTimeStr}</div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="card">
                        <div class="card-header bg-light">
                            <i class="bi bi-clock-history me-1"></i> 所有权历史
                        </div>
                        <div class="card-body">
                            ${historyOwnersHtml}
                        </div>
                    </div>
                    
                    ${isOwner ? `
                    <div class="alert alert-info mt-3 mb-0">
                        <i class="bi bi-info-circle-fill me-2"></i>
                        您是该商品的所有者，可以转移或删除此商品。
                    </div>
                    ` : ''}
                </div>
                <div class="modal-footer">
                    ${actionButtonsHtml}
                </div>
            </div>
        </div>
    `;
    
    // 添加事件处理函数
    setTimeout(() => {
        // 转移按钮
        const transferBtn = modalDiv.querySelector('.transfer-modal-btn');
        if (transferBtn) {
            transferBtn.addEventListener('click', function() {
                const goodsId = this.getAttribute('data-goods-id');
                
                // 关闭模态框
                bootstrap.Modal.getInstance(modalDiv).hide();
                
                // 填充转移表单并滚动到位置
                document.getElementById('transferId').value = goodsId;
                document.querySelectorAll('.section-card')[3].scrollIntoView({ behavior: 'smooth' });
                
                // 显示转移提示
                alert(`请在转移面板中选择接收者并完成转移操作。`);
            });
        }
        
        // 删除按钮
        const removeBtn = modalDiv.querySelector('.remove-modal-btn');
        if (removeBtn) {
            removeBtn.addEventListener('click', function() {
                const goodsId = this.getAttribute('data-goods-id');
                
                if (confirm(`确定要删除ID为 ${goodsId} 的商品吗？此操作不可恢复！`)) {
                    // 关闭模态框
                    bootstrap.Modal.getInstance(modalDiv).hide();
                    
                    // 执行删除操作
                    document.getElementById('removeId').value = goodsId;
                    document.getElementById('removeGoodsBtn').click();
                }
            });
        }
    }, 100);
    
    return modalDiv;
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 初始化Web3
    initWeb3();
    
    // 初始化账户显示
    updateAccountDisplay();
    
    // 添加账户选择变更监听器
    document.getElementById('accountSelect').addEventListener('change', handleAccountChange);
    
    // 添加按钮事件监听器
    document.getElementById('addGoodsBtn').addEventListener('click', addGoods);
    document.getElementById('queryGoodsBtn').addEventListener('click', queryGoods);
    document.getElementById('updateGoodsBtn').addEventListener('click', updateGoods);
    document.getElementById('transferGoodsBtn').addEventListener('click', transferGoods);
    document.getElementById('removeGoodsBtn').addEventListener('click', removeGoods);
    document.getElementById('resetGoodsIdBtn').addEventListener('click', resetGoodsId);
    
    // 添加刷新商品列表按钮监听器
    document.getElementById('refreshGoodsListBtn').addEventListener('click', getGoodsList);
    
    // 初始加载商品列表
    getGoodsList();
}); 